package com.schoolinfo.daoimpl;
// default package

import java.sql.Timestamp;
import java.util.List;
import java.util.Set;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.schoolinfo.dao.GoodsDAO;
import com.schoolinfo.model.Goods;

/**
 	* A data access object (DAO) providing persistence and search support for Goods entities.
 			* Transaction control of the save(), update() and delete() operations 
		can directly support Spring container-managed transactions or they can be augmented	to handle user-managed Spring transactions. 
		Each of these methods provides additional information for how to configure it for the desired type of transaction control. 	
	 * @see .Goods
  * @author MyEclipse Persistence Tools 
 */

public class GoodsDAOImpl extends HibernateDaoSupport implements GoodsDAO  {
	     private static final Logger log = LoggerFactory.getLogger(GoodsDAOImpl.class);
		//property constants
	public static final String NAME = "name";
	public static final String TYPE = "type";
	public static final String STATE = "state";
	public static final String PIC = "pic";
	public static final String CONTACT_NAME = "contactName";
	public static final String PLACE = "place";
	public static final String HOT = "hot";
	public static final String DESCRIBE = "describe";



	protected void initDao() {
		//do nothing
	}
    
    /* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#save(com.schoolinfo.model.Goods)
	 */
    @Override
	public void save(Goods transientInstance) {
        log.debug("saving Goods instance");
        try {
            getHibernateTemplate().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
    
	/* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#delete(com.schoolinfo.model.Goods)
	 */
	@Override
	public void delete(Goods persistentInstance) {
        log.debug("deleting Goods instance");
        try {
            getHibernateTemplate().delete(persistentInstance);
            getHibernateTemplate().flush();
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
    
    /* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#findById(java.lang.Integer)
	 */
    @Override
	public Goods findById( java.lang.Integer id) {
        log.debug("getting Goods instance with id: " + id);
        try {
            Goods instance = (Goods) getHibernateTemplate()
                    .get("com.schoolinfo.model.Goods", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    
    /* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#findByExample(com.schoolinfo.model.Goods)
	 */
    @Override
	public List<Goods> findByExample(Goods instance) {
        log.debug("finding Goods instance by example");
        try {
            List<Goods> results = (List<Goods>) getHibernateTemplate().findByExample(instance); 
            log.debug("find by example successful, result size: " + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }    
    
    /* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#findByProperty(java.lang.String, java.lang.Object)
	 */
    @Override
	public List findByProperty(String propertyName, Object value) {
      log.debug("finding Goods instance with property: " + propertyName
            + ", value: " + value);
      try {
         String queryString = "from Goods as model where model." 
         						+ propertyName + "= ?";
		 return getHibernateTemplate().find(queryString, value);
      } catch (RuntimeException re) {
         log.error("find by property name failed", re);
         throw re;
      }
	}

	/* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#findByName(java.lang.Object)
	 */
	@Override
	public List<Goods> findByName(Object name
	) {
		return findByProperty(NAME, name
		);
	}
	
	/* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#findByType(java.lang.Object)
	 */
	@Override
	public List<Goods> findByType(Object type
	) {
		return findByProperty(TYPE, type
		);
	}
	
	/* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#findByState(java.lang.Object)
	 */
	@Override
	public List<Goods> findByState(Object state
	) {
		return findByProperty(STATE, state
		);
	}
	
	/* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#findByPic(java.lang.Object)
	 */
	@Override
	public List<Goods> findByPic(Object pic
	) {
		return findByProperty(PIC, pic
		);
	}
	
	/* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#findByContactName(java.lang.Object)
	 */
	@Override
	public List<Goods> findByContactName(Object contactName
	) {
		return findByProperty(CONTACT_NAME, contactName
		);
	}
	
	/* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#findByPlace(java.lang.Object)
	 */
	@Override
	public List<Goods> findByPlace(Object place
	) {
		return findByProperty(PLACE, place
		);
	}
	
	/* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#findByHot(java.lang.Object)
	 */
	@Override
	public List<Goods> findByHot(Object hot
	) {
		return findByProperty(HOT, hot
		);
	}
	
	/* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#findByDescribe(java.lang.Object)
	 */
	@Override
	public List<Goods> findByDescribe(Object describe
	) {
		return findByProperty(DESCRIBE, describe
		);
	}
	

	/* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#findAll()
	 */
	@Override
	public List findAll() {
		log.debug("finding all Goods instances");
		try {
			String queryString = "from Goods";
		 	return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
    /* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#merge(com.schoolinfo.model.Goods)
	 */
    @Override
	public Goods merge(Goods detachedInstance) {
        log.debug("merging Goods instance");
        try {
            Goods result = (Goods) getHibernateTemplate()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    /* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#attachDirty(com.schoolinfo.model.Goods)
	 */
    @Override
	public void attachDirty(Goods instance) {
        log.debug("attaching dirty Goods instance");
        try {
            getHibernateTemplate().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
    
    /* (non-Javadoc)
	 * @see com.schoolinfo.daoimpl.GoodsDAO#attachClean(com.schoolinfo.model.Goods)
	 */
    @Override
	public void attachClean(Goods instance) {
        log.debug("attaching clean Goods instance");
        try {
            getHibernateTemplate().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

	public static GoodsDAO getFromApplicationContext(ApplicationContext ctx) {
    	return (GoodsDAO) ctx.getBean("GoodsDAO");
	}
	
	/**
	 * 查找最热的n个商品
	 * @return
	 */
	public List findHotList(int n){
		log.debug("finding hot Goods instances");
		List list=null;
		try {
			
			String queryString = "from Goods order by hot desc";
			Transaction t=getHibernateTemplate().getSessionFactory().getCurrentSession().beginTransaction();
			Query query =getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(queryString);
			list= query.setMaxResults(n).list();
			t.commit();
		 	return list;
		} catch (RuntimeException re) {
			log.error("find hot list failed", re);
			throw re;
		}
	}
	
	/**
	 * 查找最热的n个商品
	 * @return
	 */
	public List findBySecondId(int id){
		log.debug("finding by secondId instances");
	//	List list=null;
		try {
			
			String queryString = "from Goods g where g.secondClass.id="+id+" order by publishTime desc";
			Transaction t=getHibernateTemplate().getSessionFactory().getCurrentSession().beginTransaction();
			List list = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(queryString).list();
			t.commit();
			return list;			
		} catch (RuntimeException re) {
			log.error("find hot list failed", re);
			throw re;
		}
	}
	

	/**
	 * 按时间顺序查找从start开始长度为length的记录
	 * @param type 0：全部；1：卖 ； 2：买
	 * @param start
	 * @param length
	 * @return
	 */
	public List findAllScope(String type,int start,int length){
		log.debug("finding findByAll");
	//	List list=null;
		try {
			String queryString="";
			if(type==null || type.equals("") ||type.equals("0")){//全部
				 queryString = "from Goods  order by publishTime desc";//publishTime desc";
			}else{//根据具体type查询
				queryString = "from Goods g where g.type="+type+" order by publishTime desc";//publishTime desc";
			}
			Transaction t=getHibernateTemplate().getSessionFactory().getCurrentSession().beginTransaction();
			Query query =getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(queryString)
												.setFirstResult(start)
												.setMaxResults(length);
			List list =query.list();
			t.commit();	
			return list;
			//list= query.setMaxResults(n).list();
		//	
		 //	return list;
		} catch (RuntimeException re) {
			log.error("find hot list failed", re);
			throw re;
		}
	}
	
	
	public List findByTitle(String title,int start,int length){
		log.debug("finding findByTitle");
		try {
			String queryString = "from Goods g where g.name like '%"+title+"%' order by publishTime desc";//publishTime desc";
			
			Transaction t=getHibernateTemplate().getSessionFactory().getCurrentSession().beginTransaction();
			Query query =getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(queryString)
												.setFirstResult(start)
												.setMaxResults(length);
			List list =query.list();
			t.commit();	
			return list;
			
		} catch (RuntimeException re) {
			log.error(" findByTitle list failed", re);
			throw re;
		}
	}
	
	public int findByTitleCount(String title){
		log.debug("finding findByTitle");
		try {
			String queryString = "from Goods g where g.name like '%"+title+"%' order by publishTime desc";//publishTime desc";
			
			Transaction t=getHibernateTemplate().getSessionFactory().getCurrentSession().beginTransaction();
			Query query =getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(queryString);
			int count =query.list().size();
			t.commit();	
			return count;
			
		} catch (RuntimeException re) {
			log.error(" findByTitle list failed", re);
			throw re;
		}
	}
	
	public List findByUserId(String userId)
	{
		log.debug("finding findByUserId");
		try {
			String queryString = "select * from goods g where g.userId='"+userId+"' order by publishTime desc";//publishTime desc";
			
			Transaction t=getHibernateTemplate().getSessionFactory().getCurrentSession().beginTransaction();
			List list =  getHibernateTemplate().getSessionFactory().getCurrentSession()
					.createSQLQuery(queryString)
					.addEntity(Goods.class)
					.list();
		
			t.commit();
			
			return list;
			
		} catch (RuntimeException re) {
			log.error(" findByUserId list failed", re);
			throw re;
		}
	}
	
	
	public List findByUserId(String userId,int start,int offset)
	{
		log.debug("finding findByUserId");
		try {
			String queryString = "select * from goods g where g.userId='"+userId+"' order by publishTime desc";//publishTime desc";
			
			Transaction t=getHibernateTemplate().getSessionFactory().getCurrentSession().beginTransaction();
			List list = ((SQLQuery) getHibernateTemplate().getSessionFactory().getCurrentSession()
					.createSQLQuery(queryString)
					.setFirstResult(start)
					.setMaxResults(offset))
					.addEntity(Goods.class)
					.list();
		
			t.commit();
			
			return list;
			
		} catch (RuntimeException re) {
			log.error(" findByUserId list failed", re);
			throw re;
		}
	}
	
	public void update(Goods instance) {
        log.debug("update Goods instance");
        try {
            getHibernateTemplate().update(instance);
            getHibernateTemplate().flush();
            log.debug("update successful");
        } catch (RuntimeException re) {
            log.error("update failed", re);
            throw re;
        }
    }
	
}